package com.woniuxy.health.customer.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.health.aspect.OperationLogAnnotation;
import com.woniuxy.health.customer.vo.PageVO;
import com.woniuxy.health.customer.vo.UserWalkVO;
import com.woniuxy.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.woniuxy.health.customer.service.IUserWalkService;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * <p>
 * 走步表 前端控制器
 * </p>
 *
 * @author woniuxy
 * @since 2023-09-04
 */
@RestController
@CrossOrigin
@RequestMapping("/userWalk")
public class UserWalkController {

    private final IUserWalkService userWalkServiceImpl;
    private final RedisTemplate redisTemplate;
    @Autowired
    public UserWalkController(IUserWalkService userWalkServiceImpl, RedisTemplate redisTemplate){
        this.userWalkServiceImpl = userWalkServiceImpl;
        this.redisTemplate = redisTemplate;
    }


    //分页查询
    @GetMapping("/page")
    public Result findAllPage( Integer pageSize,
                               Integer pageNum,
                               String tel,
                               Integer walkStep){
        Page<UserWalkVO> page = Page.of(pageNum,pageSize);
        PageVO<UserWalkVO> pageVO = userWalkServiceImpl.getPage(page, tel, walkStep);
        return Result.ok(pageVO);
    }

    //导出
    @OperationLogAnnotation(module = "用户走步记录", type = "导出excel", description = "导出用户走步记录")
    @PostMapping("/import")
    public void ExcelImport(HttpServletResponse response, Integer pageSize,
                            Integer pageNum,
                            String tel,
                            Integer state) throws IOException {

        Page<UserWalkVO> page = Page.of(pageNum,pageSize);
        //查询数据方法
        PageVO<UserWalkVO> allPage = userWalkServiceImpl.getPage(page, tel,state);

        //设置请求类型
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置请求头,这里URLEncoder.encode可以防止中文乱码,当然和easyexcel没有关系
        String fileName = URLEncoder.encode("走步表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");


        System.out.println(allPage.getRecords());
        // write()
        //1.参数一:输出流
        //2.参数二:导出所参考的实体类
        //sheet()
        //1.参数一:表格名称
        //dowrite()
        //1.参数一:传输数据
        EasyExcel.write(response.getOutputStream(), UserWalkVO.class)
                .sheet("sheet0")
                .doWrite(allPage.getRecords());

    }

}
